<template>
  <div class="main_box">
    <a-row v-show="store.state.user?.curUser?.userRole!=AccessEnum.ADMIN">
      <dic id="calend_box"/>
    </a-row>
    <a-card>
      <div class="search_box">
        <a-row :gutter="5">
          <a-col :span="2" class="search_title_font">
            标题
          </a-col>

          <a-col :span="5">
            <a-input
              size="large"
              placeholder="请输入标题"
              v-model="searchTeamName"
              allow-clear />
          </a-col>

          <a-col :span="2"  class="search_title_font">
            标签
          </a-col>
          <a-col :span="5">
            <a-input
              size="large"
              placeholder="请输入标签"
              v-model="searchTeamTag"
              allow-clear />
          </a-col>
          <a-col :span="1"></a-col>
          <a-col :span="6">
            <a-input
              size="large"
              placeholder="请输入搜索"
              v-model="searchKey"
              allow-clear />
          </a-col>

          <a-col :span="2">
            <a-button @click="searchByNameTag" type="primary">
              搜索
            </a-button>
          </a-col>
          <a-col :span="1">
            <icon-plus :style="{fontSize:'20px', cursor: 'point'}"
                       @click="addQuestion"
                       v-if="store.state.user?.curUser?.userRole == AccessEnum.ADMIN"/>
          </a-col>
        </a-row>
      </div>
      <a-table class="main_table"
               :columns="columns"
               :data="itemList"
               size="large"
               style="min-height: 656px;"
               @row-click="doTeam">
        <template #tags="{record}">
          <a-tag v-for="tag in record.tags" :key="tag.id" color="green" style="margin-right: 5px">
            {{ tag }}
          </a-tag>
        </template>
        <template #submitslot="{record}">
          {{ record?.acceptednum }} / {{ record?.submitnum }}
        </template>
        <!--      <template #difficult="{ recorde }">-->
        <!--        <a-space >-->
        <!--          {{ 1.0 * recorde?.acceptednum / recorde?.submitnum < 0.3 ? '简单' : recorde?.acceptednum / recorde?.submitnum < 0.6 ? '中等' : '困难' }}-->
        <!--        </a-space>-->
        <!--      </template>-->
        <template #pagination-right>
          <icon-sun-fill />
        </template>
        <template #pagination-left>
          <icon-sun-fill />
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from "vue";
import store from "@/store";
import AccessEnum from "@/access/accessEnum";
import { QuestionControllerService, QuestionSubmitControllerService, UserControllerService } from "../../generated";
import { Message } from "@arco-design/web-vue";
import router from "@/router";
import * as echarts from 'echarts';

const itemList = reactive([]);
const searchTeamName = ref();
const searchTeamTag = ref();
const searchKey = ref();
const yearSubmitTimesMap = ref();
onMounted(async () => {
  // 请求题目
  let res = await QuestionControllerService.listQuestionUsingPost();
  let {code, msg} = res;
  console.log('res', res);
  if(code === 0) {
    itemList.length=0;
    itemList.push(...res.data);
  }else {
    Message.error(msg);
  }
  let uid = store.state.user?.curUser?.id;
  if(uid) {
    // 请求这一年每天的提交次数
    res = await QuestionSubmitControllerService.getSubmitCountByYearUsingGet(uid);
    console.log('yearSubmitTimesMap', res);
    if (res.code === 0) {
      yearSubmitTimesMap.value = res.data;
    }
  }
  const getVirtualData = (year) => {
    const startDay = +echarts.time.parse(year + '-01-01');
    // const end = +echarts.time.parse(+year + 1 + '-01-01');
    const dayTime = 3600 * 24 * 1000;
    const data = [];
    for (const k in yearSubmitTimesMap.value) {
      let tarr = yearSubmitTimesMap.value[k];
      for (let t in tarr) {
        data.push([
          echarts.time.format(startDay - 1 + Number(t) * dayTime, '{yyyy}-{MM}-{dd}', false),
          tarr[t]
        ]);
      }
    }
    return data;
  }
  // 初始化热力图
  const myChart = echarts.init(document.getElementById('calend_box'));
  // 指定图表的配置项和数据
  const option = {
    title: {
      top: 30,
      left: 'center',
      text: 'Daily Submit Count'
    },
    tooltip: {},
    visualMap: {
      min: 0,
      max: 500,
      type: 'piecewise',
      orient: 'horizontal',
      left: 'center',
      top: 65
    },
    calendar: {
      top: 120,
      left: 30,
      right: 30,
      cellSize: ['auto', 13],
      range: '2024',
      itemStyle: {
        borderWidth: 0.5
      },
      yearLabel: { show: false }
    },
    series: {
      type: 'heatmap',
      coordinateSystem: 'calendar',
      data: getVirtualData('2024')
    }
  };
  myChart.setOption(option);

})

const columns = [
  {
    title: '题号',
    dataIndex: 'id'
  }, {
    title: '标题',
    dataIndex: 'title',
  }, {
    title: '提交',
    slotName: 'submitslot',
  }, {
    title: '标签',
    slotName: 'tags'
  },
];

const searchByNameTag = async () => {
  if (searchKey.value) {
   let res = await QuestionControllerService.searchPostVoByPageUsingPost({
     searchText: searchKey.value,
     tags: JSON.stringify(searchTeamTag.value),
     title:searchTeamName.value,
     pageSize: 15,
     current: 1
   });
   if (res.code == 0) {
     console.log('test', res.data.records);
     itemList.length=0;
     itemList.push(...res.data.records);
     return;
   }
  }

  let searchTeamTagTp = searchTeamTag.value;
  let searchTeamNameTp = searchTeamName.value;
  console.log('searchTeamTag', searchTeamTag.value);
  console.log('searchTeamName', searchTeamName.value);
  // 未填信息
  if (!searchTeamTagTp) searchTeamTagTp = '_';
  if (!searchTeamNameTp) searchTeamNameTp = '_';
  let res = await QuestionControllerService.listQuestionByTagTitleUsingGet(
    searchTeamTagTp,
    searchTeamNameTp);
  console.log('res.data', res.data);
  if ( res.code == 0) {
    itemList.length=0;
    itemList.push(...res.data);
  }else {
    Message.error("搜索失败");
  }
  console.log('search team');
}
const doTeam = (team:any , ev: any) => {
  console.log('search team', team);
  console.log('search ev', ev);
  const userRole = store.state.user.curUser.userRole;
  // 判断权限 如果是user
  if (userRole == AccessEnum.USER) {
    // 跳转做题页面（传递题目数据）
    router.push({ path: '/submit_team', query: { id: team.id } });
  }else if (userRole == AccessEnum.ADMIN) {
    // 跳转到管理题目页面
    router.push({ path: '/managerTeam', query: { id: team.id } });
  }else if (userRole == AccessEnum.NOT_LOGIN) {
    // 跳转到登录页面
    router.push({ path: '/user/login'});
  }
  // router.push({path: `/submit_team?id=${team.id}`});
}
const addQuestion = () => {
  router.push({
    path: `/addTeam`
  })
}
const getLoginUser = async () => {
  const res = await UserControllerService.getLoginUserUsingGet();
  console.log('res:', res);
}
</script>

<style scoped>
.main_box{
  height: 100%;
  width: 100%;
}
.search_box {
  margin-top: 20px;
  margin-bottom: 20px;
}
.main_table {
  width: 100%;
}
.arco-space {
  display: block;
}
tr {
  height: 60px;
}
.search_title_font {
  font-weight: bold;
  text-align: center;
  color: #4c5a69;
  line-height: 35px;
}
#calend_box {
  width: 1200px;
  height: 250px;
  margin: 0 auto;
}
</style>